﻿using System;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Eneta.Portal.Common.Services
{
    public class MailerService
    {
        public void SendMailByTemplate(string templateName, string userName, string itemName, string itemUrl, string[] addresses)
        {
            var repository = new EmailTemplateRepository(SPContext.Current.Web);
            
            var template = repository.GetEmailTemplateByName(templateName);
            if (template == null)
                throw new Exception("E-mail template not found: " + templateName);

            var title = ReplaceTags(template.TitleTemplate, userName, itemName, itemUrl);
            var body = ReplaceTags(template.BodyTemplate, userName, itemName, itemUrl);

            foreach(var address in addresses)
            {
                SPUtility.SendEmail(SPContext.Current.Web, false, false, address, title, body);
            }
        }

        private string ReplaceTags(string text, string userName, string itemName,string itemUrl)
        {
            if (string.IsNullOrEmpty(text))
                return text;

            text = text.Replace("{USER}", userName);
            text = text.Replace("{ITEMNAME}", itemName);
            text = text.Replace("{ITEMURL}", itemUrl);

            return text;
        }
    }
}
